package com.github.wujichen158.andemusic.network;

import com.google.common.base.Charsets;
import io.netty.buffer.ByteBuf;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;

public class MusicMessage implements IMessage {
    public String musicType;
    public int minTime;
    public int maxTime;

    public MusicMessage() {
    }

    public MusicMessage(String musicType, int minTime, int maxTime) {
        this.musicType = musicType;
        this.minTime = minTime;
        this.maxTime = maxTime;
    }

    @Override
    public void fromBytes(ByteBuf buf) {
        int length = buf.readInt();
        byte[] readBytes = new byte[length];
        buf.readBytes(readBytes);
        this.musicType = new String(readBytes, Charsets.UTF_8);

        this.minTime = buf.readInt();
        this.maxTime = buf.readInt();
    }

    @Override
    public void toBytes(ByteBuf buf) {
        byte[] bytes = this.musicType.getBytes(Charsets.UTF_8);
        buf.writeInt(bytes.length);
        buf.writeBytes(bytes);

        buf.writeInt(this.minTime);
        buf.writeInt(this.maxTime);
    }

    /**
     * Only Client handle this msg
     */
    public static class MusicMsgHandler implements IMessageHandler<MusicMessage, IMessage> {
        @Override
        public IMessage onMessage(MusicMessage message, MessageContext ctx) {
            if (ctx.side.isClient()) {
                ClientMsgHandler.handleClientMsg(message);
            }
            return null;
        }
    }
}